package com.jl.card.parse;

import java.util.Arrays;

import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.annotations.JSConstructor;
import org.mozilla.javascript.annotations.JSFunction;

import com.jl.util.HexUtil;
import com.jl.util.LengthUtil;

public class Parser extends ScriptableObject implements IParse{

	private final static String clazzName = "Parser";

	private byte[] cmd = null;
	private byte[] res = null;

	private byte[] data = null;
	private byte[] sw = new byte[2];
	private int intSW = 0x9000;
	private String swInfo = "";

	public Parser() {
	}

	@JSConstructor
	public Parser(String strCmd, String strRes) {
		strCmd = LengthUtil.replace(strCmd);
		cmd = HexUtil.parseHexToByteArray(strCmd);
		res = HexUtil.parseHexToByteArray(strRes);
		if (res.length < 2) {
			throw new RuntimeException("Response Data Wrong");
		} else {
			sw[0] = res[res.length - 2];
			sw[1] = res[res.length - 1];
			intSW = HexUtil.makeShort(sw, 0) & 0xFFFF;
			if (res.length > 2) {
				data = Arrays.copyOfRange(res, 0, res.length - 2);
			} else {
				data = new byte[0];
			}
			swInfo = "SW   = " + HexUtil.toHexString(sw) + '('
					+ StatusWordTable.StringForSW(intSW) + ')';
		}
		beginParse();
	}

	private void beginParse() {
		// TODO Auto-generated method stub

	}

	@JSFunction
	public String parse() {
		StringBuilder sb = new StringBuilder();
		sb.append("DATA = ").append(HexUtil.toHexString(data)).append('\n');

		//add more 
		
		sb.append(swInfo);
		return sb.toString();
	}

	@Override
	@JSFunction
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("DATA = ").append(HexUtil.toHexString(data)).append('\n');

		sb.append(swInfo);
		return sb.toString();
	}

	@Override
	public String getClassName() {
		return clazzName;
	}

}
